package com.itheima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.domain.DTO.LoginDTO;
import com.itheima.domain.pojo.Emp;
import com.itheima.domain.pojo.EmpExpr;
import com.itheima.domain.pojo.EmpLog;
import com.itheima.domain.query.QueryParam;
import com.itheima.domain.vo.LoginVO;
import com.itheima.domain.vo.PageResult;
import com.itheima.domain.vo.Result;
import com.itheima.exception.CustomerException;
import com.itheima.mapper.EmpMapper;
import com.itheima.mapper.ExprMapper;
import com.itheima.oss.AliyunOSSOperator;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * @Author:篍
 * @Date: 2025/07/11 15:16
 * @Description:
 */
@Service
@Slf4j
public class EmpServiceImpl implements EmpService {
    @Autowired
    EmpMapper empMapper;

    @Autowired
    ExprMapper exprMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        Emp dbEmp = empMapper.findEmpById(emp.getId());
        //数据库存储的用户名和手机号
        String dbEmpUsername = dbEmp.getUsername();
        String dbEmpPhone = dbEmp.getPhone();
        //接收的用户名
        String receiveUsername = emp.getUsername();
        //接收的手机号
        String phone =emp.getPhone();
        if (!StrUtil.equals(dbEmpUsername,receiveUsername)){
            //用户名是否已存在
            Integer usernameIfExist = empMapper.findUsernameIfExist(receiveUsername);
            if (usernameIfExist>0){
                throw new CustomerException(receiveUsername+"用户名已存在");
            }
        }

        if (!StrUtil.equals(dbEmpPhone,phone)){
            //手机号是否已存在
            Integer phoneIfExist = empMapper.findPhoneIfExist(phone);
            if (phoneIfExist>0){
                throw new CustomerException(phone+"手机号已存在");
            }
        }


        //改修改时间
        emp.setUpdateTime(LocalDateTime.now());

        //删除工作经历
        exprMapper.deleteByEmpIds(new Integer[]{emp.getId()});

        //修改员工表
        empMapper.updateEmp(emp);

        //修改工作经历表
        //补全工作经历对应的员工ID
        if (CollectionUtil.isNotEmpty(emp.getExprList())) {
             addEmpIdToExpr(emp);
             exprMapper.addExpr(emp.getExprList());
        }

    }

    @Autowired
    EmpLogService empLogService;

    @Autowired
    AliyunOSSOperator aliyunOSSOperator;

    @Override
    public Emp findEmpById(Integer id) {
        return empMapper.findEmpById(id);
    }

    @Override
    public PageResult<Emp> empPage(QueryParam empQueryParam) {
        PageHelper.startPage(empQueryParam.getPage(),empQueryParam.getPageSize());
        Page<Emp> emps=empMapper.empPage(empQueryParam);
        return new PageResult<>(emps.getTotal(),emps.getResult());
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addEmpAndExpr(Emp emp) {
        try {
            emp.setPassword("how are you");
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            empMapper.addEmp(emp);
            log.info("id={}",emp.getId());
            if (CollectionUtil.isNotEmpty(emp.getExprList())) {
                addEmpIdToExpr(emp);
                exprMapper.addExpr(emp.getExprList());
            }
        } finally {
            EmpLog empLog= EmpLog.builder()
                    .operateTime(LocalDateTime.now())
                    .info(emp.toString())
                    .build();
            empLogService.insertLog(empLog);
        }
    }

    public  void  addEmpIdToExpr(Emp emp) {
        //补全工作经历对应的员工ID
        for (EmpExpr empExpr : emp.getExprList()) {
            empExpr.setEmpId(emp.getId());
        }
    }

    @Override
    public List<Emp> findAllEmp() {
        return empMapper.findAllEmp();
    }

    /**
     * 根据员工id数组删除员工和对应的工作经历和阿里云的头像
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIds(Integer[] ids) throws Exception {

        List<String> keys=empMapper.getImagesByIds(ids);

        //删除员工
        empMapper.deleteByIds(ids);
        exprMapper.deleteByEmpIds(ids);

        aliyunOSSOperator.deleteByUrls(keys);

    }

    @Override
    public LoginVO login(LoginDTO loginDTO) {
        String username=loginDTO.getUsername();
        String password=loginDTO.getPassword();
        if (StrUtil.isBlank(username)||StrUtil.isBlank(password)){
            throw new CustomerException("用户名或者密码不可为空");
        }
        Emp emp=empMapper.findEmpByUsername(username);
        if (ObjUtil.isNull(emp)){
            throw new CustomerException("该用户不存在");
        }else if (!StrUtil.equals(emp.getPassword(),password)){
            throw new CustomerException("用户名或者密码错误");
        }else {
            //        2.3状态判断(无)
//        3.封装数据
            HashMap<String, Object> claims = new HashMap<>();

            claims.put("id",emp.getId());
            claims.put("username",emp.getUsername());


            String jwt = JwtUtils.generateJwt(claims);

            return LoginVO.builder()
                    .id(emp.getId())
                    .username(emp.getUsername())
                    .name(emp.getName())
                    .token(jwt)
                    .build();
        }
    }

    @Override
    public Result login1(LoginDTO loginDTO) {
        String username=loginDTO.getUsername();
        String password=loginDTO.getPassword();
        if (StrUtil.isBlank(username)||StrUtil.isBlank(password)){
            return Result.error("不可为空");
        }
        Emp emp=empMapper.findEmpByUsername(username);
        if (ObjUtil.isNull(emp)){
            return Result.error("该用户不存在");
        }else if (!StrUtil.equals(emp.getPassword(),password)){
            return Result.error("用户名或者密码错误");
        }else {
            //        2.3状态判断(无)
//        3.封装数据
            HashMap<String, Object> claims = new HashMap<>();

            claims.put("id",emp.getId());
            claims.put("username",emp.getUsername());


            String jwt = JwtUtils.generateJwt(claims);

            LoginVO loginVO = LoginVO.builder()
                    .id(emp.getId())
                    .username(emp.getUsername())
                    .name(emp.getName())
                    .token(jwt)
                    .build();
            return Result.success(loginVO);
        }
    }
}
